<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // let P1 = new Promise(function (resolve, reject) {
      //   setTimeout(() => {
      //     resolve(true);
      //   }, 200);
      // });
      // let P2 = new Promise(function (resolve, reject) {
      //   setTimeout(() => {
      //     resolve(true);
      //   }, 200);
      // });
      // let P3 = new Promise(function (resolve, reject) {
      //   setTimeout(() => {
      //     resolve(true);
      //   }, 200);
      // });
      const FULL_FILLED = "fullFilled"; // 成功
      const REJECTED = "rejected"; // 失败
      const PENDING = "pending"; //这里用的setTimeout做异步操作，所以在执行异步之前的时间里，状态都是pending
      class MyPromise {
        constructor(fn) {
          this.status = PENDING;
          this.arr = [];
          this.fn = fn;
          let resolve = (value) => {
            this.status = FULL_FILLED;
            this.value = value;
            this.arr.forEach((val) => {
              val();
            });
          };
          fn(resolve);
        }
        then(fn) {
          console.log(1);
          let chainPromise;
          if (this.status === "pending") {
            chainPromise = new MyPromise((resolve, reject) => {
              this.arr.push(() => {
                let thenValue = fn(this.value);
                resolve(thenValue);
              });
            });
          } else if (this.status === "fullFilled") {
            fn(this.value);
          }
          return chainPromise;
        }
      }

      new MyPromise(function (resolve) {
        setTimeout(() => {
          resolve(true);
        }, 200);
      })
        .then((val) => {
          console.log(val);
          return "222";
        })
        .then((val2) => {
          console.log(val2);
        });
    </script>
  </body>
</html>
